import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:im_app/im/page/bloc/ContentSearchCubit.dart';
import 'package:im_app/im/page/bloc/WebRtcCubit.dart';
import 'package:provider/provider.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
import 'package:window_size/window_size.dart';

import 'SimpleBlocObserver.dart';
import 'im/emojiOne/EmojiOneInfoes.dart';
import 'im/page/MessageSendPage.dart';
import 'im/page/MessageSendPage0.dart';
import 'im/page/bloc/GroupSelectCubit.dart';
import 'im/page/bloc/LoginCubit.dart';
import 'im/page/bloc/MessageHistoryCubit.dart';
import 'im/page/bloc/MessageHistoryDayCubit.dart';
import 'im/page/bloc/SessionCubit.dart';
import 'im/page/bloc/SessionListCubit.dart';
import 'im/page/bloc/UserAndGroupListCubit.dart';
import 'im/page/bloc/UserListCubit.dart';
import 'im/page/bloc/WorkbenchCubit.dart';
import 'im/util/FileUtil.dart' as futil;
import 'im/util/IsolatePoolUtil.dart';
import 'page/LoginPage.dart';
import 'page/MainPage.dart';
import 'im/page/sub/ContentSearchPage.dart';
import 'im/util/DbUtil.dart';
import 'im/util/ImSingleton.dart';

void main() async {
  Bloc.observer = const SimpleBlocObserver();
  WidgetsFlutterBinding.ensureInitialized();
  // PowerFileViewManager.initEngine();

  setupWindow();

  await EmojiOneInfoes.getInstance().loadData();

  // init sqflite
  if (Platform.isWindows || Platform.isLinux || Platform.isMacOS) {
    sqfliteFfiInit();
    databaseFactory = databaseFactoryFfi;
    Database database = await DbUtil.connect("im.db");
    ImSingleton.getInstance().dataBase = database;
  } else if (Platform.isAndroid) {
    databaseFactory = databaseFactory;
    Database database = await DbUtil.connect("im.db");
    ImSingleton.getInstance().dataBase = database;
  }

  ImSingleton.getInstance().session.putData("im_ip", "192.168.1.6");
  String rootDir = await futil.FileUtil.getFileRoot();
  ImSingleton.getInstance().rootDir = rootDir;
  runApp(const ImApp());
  print("start !!!!!!!!!!!!!");
}

const double windowWidth = 414;
const double windowHeight = 896;

void setupWindow() {
  if (!kIsWeb && (Platform.isWindows || Platform.isLinux || Platform.isMacOS)) {
    WidgetsFlutterBinding.ensureInitialized();
    setWindowTitle('Im App');
    setWindowMinSize(const Size(windowWidth, windowHeight));
    setWindowMaxSize(const Size(windowWidth, windowHeight));
    getCurrentScreen().then((screen) {
      setWindowFrame(Rect.fromCenter(
        center: screen!.frame.center,
        width: windowWidth,
        height: windowHeight,
      ));
    });
  }
}

class ImApp extends StatefulWidget {
  const ImApp({super.key});

  @override
  State<StatefulWidget> createState() => _ImAppState();

}

class _ImAppState extends State<ImApp> {

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          // ChangeNotifierProvider<ReceiveDataModel>(create: (context) => ReceiveDataModel()),
          BlocProvider(create: (_) => UserListCubit()..loadData(),),
          BlocProvider(create: (_) => UserAndGroupListCubit()..loadData(),),
          BlocProvider(create: (_) => SessionListCubit()..loadData(ImSingleton.getInstance().session.userId!),),
          // BlocProvider(
          //   create: (_) => HotMessageTotalCubit()..loadData(),
          // ),
          BlocProvider(create: (_) => ContentSearchCubit(),),
          BlocProvider(create: (_) => LoginCubit()..loadData(),),
          BlocProvider(create: (_) => WorkbenchCubit()..loadData(null),),
          BlocProvider(create: (_) => GroupSelectCubit()..loadData(),),
          BlocProvider(create: (_) => SessionCubit()..loadData(),),
          BlocProvider(create: (_) => MessageHistoryDayCubit(),),
          BlocProvider(create: (_) => MessageHistoryCubit(),),
          BlocProvider(create: (_) => WebRtcCubit(),),
          // ValueListenableProvider.value(value: HotMessageTotalModel(0))
        ],
        child: MaterialApp(
          debugShowCheckedModeBanner: false,
          title: 'Im App',
          theme: ThemeData(
            visualDensity: VisualDensity.adaptivePlatformDensity,
            appBarTheme: const AppBarTheme(scrolledUnderElevation: 0),
          ),
          initialRoute: '/LoginPage',
          routes: {
            '/LoginPage': (BuildContext context) => const LoginPage(),
            '/MainPage': (BuildContext context) => const MainPage(title: ''),
            "/MessageSendPage": (BuildContext context) => const MessageSendPage0(),
            //"/EmojiPage": (BuildContext context) => new EmojiPage(),
            "/ContentSearchPage": (BuildContext context) => const ContentSearchPage(),
            // "/GroupAddPage": (BuildContext context) => new GroupAddPage(),
            //"/RtcDemoPage": (BuildContext context) => new RtcDemoPage(),
          },
        )
    );
  }

  @override
  void dispose() {
    IsolatePoolUtil.getInstance().close();
    super.dispose();
  }
}
